import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { AuthenticationService } from '../services/authentication.service';
import { LoginUser } from './loginuser';
import { RouterService } from '../services/router.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  username = new FormControl('', [
    Validators.required,
    Validators.minLength(6)]);
  password = new FormControl('', [
    Validators.required,
    Validators.minLength(6)]);
  hide = true;
  errorMessage: string;
  submitMessage: string;
  fromTitle: String;
  cimatchButton: String;
  cimatchButton2: String;

  constructor(private authService: AuthenticationService,
    private routerService: RouterService) {
  }

  ngOnInit() {
    this.errorMessage = '';
    this.submitMessage = '';
    this.username.reset();
    this.password.reset();
    this.fromTitle = 'CIMATCH LOGIN';
    this.cimatchButton = 'LOGIN';
    this.cimatchButton2 = 'REGISTER';

  }

  cimatchSubmit() {

    if (this.username && this.username.errors) {
      this.errorMessage = 'username has error!';
    }
    if (this.password && this.password.errors) {
      this.errorMessage  = ' password has error!';
    }
    const loginUser = {
      userId: this.username.value,
      userPassword: this.password.value
    };
    if (this.cimatchButton === 'LOGIN') {
      this.authService.authenticateUser(loginUser).subscribe(res => {
        this.authService.setBearerToken(res['token']);
        this.authService.setUserId(loginUser.userId);
        this.routerService.routeToDashboard();
      }, error => {
        this.submitMessage = (error.error != null) ? error.error.message : error.message;
      });
    }

    if (this.cimatchButton === 'REGISTER') {
      this.authService.registerUser(loginUser).subscribe(res => {
        this.ngOnInit();
      }, error => {
        this.submitMessage = (error.error != null) ? error.error.message : error.message;
      });
    }


    this.username.reset();
    this.password.reset();
  }

  cimatchSwitch() {
    if (this.cimatchButton === 'LOGIN') {
      this.cimatchButton = 'REGISTER';
      this.cimatchButton2 = 'LOGIN';
      this.fromTitle = 'CIMATCH REGISTER';
    } else {
      this.cimatchButton = 'LOGIN';
      this.cimatchButton2 = 'REGISTER';
      this.fromTitle = 'CIMATCH LOGIN';
    }
  }
}
